package org.fireking.myapplication

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

/**
 * 图表绘图交互视图，仅负责接收用户输入并交给ChartDrawingManager处理
 * 同时绘制临时的交互状态，如拖动中的线条预览等
 */
class ChartDrawingInteractionView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 关联的绘图管理器
    private var drawingManager: ChartDrawingManager? = null

    // 当前绘制的临时路径（仅用于预览）
    private val tempPath = Path()

    // 临时点集合（仅用于预览）
    private val tempPoints = mutableListOf<Pair<Float, Float>>()

    // 临时绘制中的标志
    private var isDrawing = false

    // 预览绘制用的画笔
    private val previewPaint = Paint().apply {
        color = Color.GREEN
        strokeWidth = 3f
        style = Paint.Style.STROKE
        isAntiAlias = true
        // 虚线效果，用于区分预览和最终效果
        pathEffect = android.graphics.DashPathEffect(floatArrayOf(10f, 5f), 0f)
    }

    init {
        // 设置背景透明
        setBackgroundColor(Color.TRANSPARENT)
    }

    /**
     * 设置关联的绘图管理器
     */
    fun attachToDrawingManager(manager: ChartDrawingManager) {
        this.drawingManager = manager
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 如果处于编辑模式，不绘制预览
        if (drawingManager?.isInEditMode() == true) {
            return
        }

        if (!isDrawing || tempPoints.isEmpty()) return

        // 绘制当前正在交互的临时预览
        when (drawingManager?.drawingMode) {
            ChartDrawingManager.DrawingMode.LINE -> {
                if (tempPoints.size >= 2) {
                    canvas.drawLine(
                        tempPoints[0].first,
                        tempPoints[0].second,
                        tempPoints[1].first,
                        tempPoints[1].second,
                        previewPaint
                    )
                }
            }

            ChartDrawingManager.DrawingMode.RECTANGLE -> {
                if (tempPoints.size >= 2) {
                    val left = minOf(tempPoints[0].first, tempPoints[1].first)
                    val top = minOf(tempPoints[0].second, tempPoints[1].second)
                    val right = maxOf(tempPoints[0].first, tempPoints[1].first)
                    val bottom = maxOf(tempPoints[0].second, tempPoints[1].second)
                    canvas.drawRect(left, top, right, bottom, previewPaint)
                }
            }

            ChartDrawingManager.DrawingMode.CURVE -> {
                canvas.drawPath(tempPath, previewPaint)
            }

            else -> { /* 不绘制 */
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val manager = drawingManager ?: return false

        // 如果是编辑模式，将事件转发给绘图管理器处理
        if (manager.isInEditMode()) {
            val handled = manager.handleEditModeTouch(event.x, event.y, event.action)
            if (handled) {
                return true
            }

            // 如果编辑模式下没有处理事件，则检查是否需要将事件传递给图表
            return if (manager.drawingMode == ChartDrawingManager.DrawingMode.NONE) {
                false  // 不拦截事件，让图表处理
            } else {
                true   // 拦截事件，不让图表处理
            }
        }

        // 如果没有绘图管理器或当前不是绘图模式，不处理事件
        if (manager.drawingMode == ChartDrawingManager.DrawingMode.NONE) {
            return false
        }

        // 更新预览的画笔颜色
        previewPaint.color = manager.drawingColor
        previewPaint.strokeWidth = manager.lineWidth

        // 处理预览绘制
        val x = event.x
        val y = event.y

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isDrawing = true

                tempPoints.clear()
                tempPoints.add(Pair(x, y))

                if (manager.drawingMode == ChartDrawingManager.DrawingMode.CURVE) {
                    tempPath.reset()
                    tempPath.moveTo(x, y)
                }

                invalidate()
            }

            MotionEvent.ACTION_MOVE -> {
                if (isDrawing) {
                    when (manager.drawingMode) {
                        ChartDrawingManager.DrawingMode.LINE -> {
                            if (tempPoints.size > 1) {
                                tempPoints[1] = Pair(x, y)
                            } else {
                                tempPoints.add(Pair(x, y))
                            }
                        }

                        ChartDrawingManager.DrawingMode.RECTANGLE -> {
                            if (tempPoints.size > 1) {
                                tempPoints[1] = Pair(x, y)
                            } else {
                                tempPoints.add(Pair(x, y))
                            }
                        }

                        ChartDrawingManager.DrawingMode.CURVE -> {
                            tempPoints.add(Pair(x, y))
                            tempPath.lineTo(x, y)
                        }

                        else -> { /* 不处理 */
                        }
                    }

                    invalidate()
                }
            }

            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                isDrawing = false
                tempPoints.clear()
                tempPath.reset()
                invalidate()
            }
        }

        // 将事件传递给绘图管理器处理
        return manager.onTouchEvent(event)
    }
} 